import { Directive, ElementRef, Input, OnInit, OnChanges, OnDestroy } from '@angular/core';

import { NgEchartService } from "./ng-echart.service";

import { CategoryName } from "../../pipes/categoryNamePipe";

import { Util } from '../../utils/util';


import { AppSettings } from "../../app.settings";

import { Scope } from '../../utils/emit';

declare var echarts: any;

@Directive({
  selector: '[echarts]',
  providers: [NgEchartService, CategoryName]
})
export class NgEchartDirective {

  @Input('data') data: any;
  @Input('loading') loading: boolean;  //true -> loading  | false-> close loading
  @Input('handelFun') handelFun: Function;
  @Input('type') type: string; //chart type
  @Input('resize') resize: boolean;

  @Input('title') title: string;
  @Input('column') column: string;

  chart: any;

  constructor(private _service: NgEchartService, private el: ElementRef, private appSettings: AppSettings, private categoryName: CategoryName, private scope: Scope, private util: Util) {

    this.chart = echarts.init(this.el.nativeElement);

  }

  ngOnInit() {

    
    if (this.handelFun) {
      this.chart.on('click', this.handelFun);
    }

  }

  // watch
  ngOnChanges(changes) {

    // loading false
    if (changes.loading && (changes.loading.currentValue === false)) {
      // alert(0);

      this.setDataInit();
    } else {
      this.showLoading();
    }
  }

  // destroy
  ngOnDestroy() {
    if (this.handelFun) {
      this.chart.off('click', this.handelFun);
    }
  }

  // echarts resize
  chartResize() {
    if (this.resize) {
      // console.log(this.el.nativeElement);
      // console.log(this.el.nativeElement.height);

      let percent = document.body.clientHeight / document.body.clientWidth;

      let height = Math.floor(this.el.nativeElement.clientWidth * percent);

      if (height > this.el.nativeElement.clientHeight) {

        this.chart.resize({ width: 'auto', height: '400px' });
      } else {
        this.chart.resize({ width: 'auto', height: height + 'px' });
      }




    } else {
      this.chart.resize({ width: 'auto', height: 'auto' });
    }
  }



  showLoading() {
    this.chartResize();
    this.chart.showLoading();
  }

  public setDataInit() {
    switch (this.type) {
      case 'category-bar':
        this.categoryBarInit();
        break;
      case "pie":

        this.pieInit();
        // code...
        break;
      case "pie-cat":
        // this.chart.on('legendselectchanged',(data)=>{
        //   console.log(data);
        // });
        this.pieCatInit();
        // code...
        break;
      case "pie-brand":

        this.pieBrandInit();
        // code...
        break;

      case "bar":
        this.barInit();
        break;
      case "line-word":

        this.lineWordInit();
        // code...
        break;
      case "line-lm":

        this.lineLMInit();
        // code...
        break;
      case "line-m":

        this.lineMInit();
        // code...
        break;
      case "line-mm":

        this.lineMMInit();
        // code...
        break;
      // config
      case "line-month":

        this.lineMonthInit();
        // code...
        break;
      case "word":
        this.wordInit();

        break;

      default:
        // code...
        break;
    }
  }

  categoryBarInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;


    option.column = this.column;

    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      option.xAxis.data.push(item.date.split(' ')[0]);
      option.series[0].data.push(item.price);
      option.series[1].data.push(item.sellAmount);
    }


    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();

  }

  // 行业饼图
  private pieInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;

    option.fileName = this.title;

    let timeType = this.appSettings.getSellTimeType();

    let isLeaf: boolean = false;


    console.log(this.data);

    // 是否是叶子
    if (this.data.isLeaf) {
      console.log(this.data.isLeaf);
      isLeaf = true;
    }

    if (!isLeaf) {
      for (let i = 0; i < this.data.length; i++) {

        let item = this.data[i];

        let _catName: string = item.categoryName;
        _catName = this.categoryName.transform(_catName);

        option.legend.data.push(_catName);

        // console.log(item);
        if (i > 20) {
          option.series[0].data.push({
            name: _catName,
            wholeName: item.categoryName,
            value: timeType != "month" ? item.sellMoney : item.monthSellMoney,
            categoryId: Number(item.categoryId),
            isLeaf: item.categoryId > 0,
            label: {
              normal: {
                show: false,
                textStyle: {
                  fontSize: 12
                }
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: 14,
                  fontWeight: 800
                }
              }
            },
            labelLine: {
              normal: {
                show: false,
                smooth: true,
                lineStyle: {
                  opacity: 0.7
                },
              },
              emphasis: {
                show: true,
                lineStyle: {
                  width: 3,
                  opacity: 1
                },
              }
            }
          });
        } else {
          option.series[0].data.push({
            name: _catName,
            wholeName: item.categoryName,
            value: timeType != "month" ? item.sellMoney : item.monthSellMoney,
            isLeaf: item.categoryId > 0,
            categoryId: Number(item.categoryId),
            leafData: {
              categoryId: Number(item.categoryId),
              csellMoney: item.csellMoney,
              tsellMoney: item.tsellMoney,
              thksellMoney: item.thksellMoney,
              gsellMoney: item.gsellMoney,
              monthCSellMoney: item.monthCSellMoney,
              monthTSellMoney: item.monthTSellMoney,
              monthThkSellMoney: item.monthThkSellMoney,
              monthGSellMoney: item.monthGSellMoney
            }
          });
        }
      }
    } else {

      let leafData = this.data[0];

      // 饼图赋值
      option.series[0].data = [{
        name: '天猫',
        value: timeType != "month" ? leafData.tsellMoney : leafData.monthTSellMoney,
        click: false
      }, {
        name: '淘宝',
        value: timeType != "month" ? leafData.csellMoney : leafData.monthCSellMoney,
        click: false
      }, {
        name: '天猫国际',
        value: timeType != "month" ? leafData.thksellMoney : leafData.monthThkSellMoney,
        click: false
      }, {
        name: '全球购',
        value: timeType != "month" ? leafData.gsellMoney : leafData.monthGSellMoney,
        click: false
      }];
      option.legend.data.length = 0;
      option.legend.data = ['天猫', '淘宝', '天猫国际', '全球购'];

    }



    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();
  }

  // 饼图类目销售占比
  pieCatInit() {

    let option = this._service.generate(this.type);

    let timeType = this.appSettings.getSellTimeType();

    option.storeData = this.data;

    option.column = this.column;

    // 排序
    this.data.sort((a, b) => {
      if (timeType == 'month') {

        return b.monthSellMoney - a.monthSellMoney;

      } else {
        return b.sellMoney - a.sellMoney;
      }
    });

    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      let _catName: string = item.categoryName;
      // _catName = this.categoryName.transform(_catName);
      option.legend.data.push(_catName);

      if (i > 20) {
        option.series[0].data.push({
          name: _catName,
          value: timeType != "month" ? item.sellMoney : item.monthSellMoney,
          label: {
            normal: {
              show: false,
              textStyle: {
                fontSize: 12
              }
            },
            emphasis: {
              show: true,
              textStyle: {
                fontSize: 14,
                fontWeight: 800
              }
            }
          },
          labelLine: {
            normal: {
              show: false,
              smooth: true,
              lineStyle: {
                opacity: 0.7
              },
            },
            emphasis: {
              show: true,
              lineStyle: {
                width: 3,
                opacity: 1
              },
            }
          }
        });
      } else {
        option.series[0].data.push({
          name: _catName,
          value: timeType != "month" ? item.sellMoney : item.monthSellMoney
        });
      }



    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();
  }

  pieBrandInit() {

    let option = this._service.generate(this.type);

    let timeType = this.appSettings.getSellTimeType();

    option.storeData = this.data;

    option.column = this.column;

    // 排序
    this.data.sort((a, b) => {
      if (timeType == 'month') {

        return b.monthSellMoney - a.monthSellMoney;

      } else {
        return b.sellMoney - a.sellMoney;
      }
    });

    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];


      option.legend.data.push(item.brandName);

      if (i > 20) {
        option.series[0].data.push({
          name: item.brandName,
          value: timeType != "month" ? item.sellMoney : item.monthSellMoney,
          label: {
            normal: {
              show: false,
              textStyle: {
                fontSize: 12
              }
            },
            emphasis: {
              show: true,
              textStyle: {
                fontSize: 14,
                fontWeight: 800
              }
            }
          },
          labelLine: {
            normal: {
              show: false,
              smooth: true,
              lineStyle: {
                opacity: 0.7
              },
            },
            emphasis: {
              show: true,
              lineStyle: {
                width: 3,
                opacity: 1
              },
            }
          }
        });
      } else {
        option.series[0].data.push({
          name: item.brandName,
          value: timeType != "month" ? item.sellMoney : item.monthSellMoney
        });
      }



    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();
  }

  private barInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;

    let timeType = this.appSettings.getSellTimeType();

    let isLeaf: boolean = false;


    // console.log(this.data);

    // 是否是叶子
    if (this.data.isLeaf) {
      isLeaf = true;
    }

    if (!isLeaf) {
      for (let i = 0; i < this.data.length; i++) {

        let item = this.data[i];

        let _catName: string = item.categoryName;
        _catName = this.categoryName.transform(_catName);

        option.xAxis.data.push(_catName);
        option.series[0].data.push(timeType != "month" ? item.sellMoney : item.monthSellMoney);

      }
    } else {

      let leafData = this.data[0];

      option.xAxis.data = ['天猫', '淘宝', '天猫国际', '全球购'];

      // 饼图赋值
      option.series[0].data = [{
        name: '天猫',
        value: timeType != "month" ? leafData.tsellMoney : leafData.monthTSellMoney,
        click: false
      }, {
        name: '淘宝',
        value: timeType != "month" ? leafData.csellMoney : leafData.monthCSellMoney,
        click: false
      }, {
        name: '天猫国际',
        value: timeType != "month" ? leafData.thksellMoney : leafData.monthThkSellMoney,
        click: false
      }, {
        name: '全球购',
        value: timeType != "month" ? leafData.gsellMoney : leafData.monthGSellMoney,
        click: false
      }];


    }



    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();

  }

  lineWordInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;

    option.fileName = this.title;

    let _type = this.util.sessionStore().get('wordDetail').type;


    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      option.xAxis.data.push(item.date.split(' ')[0]);
      if (this.appSettings.getSellTimeType() != "month") {
        option.series[0].data.push(item.sellMoney);
        option.series[1].data.push(item.sellAmount);

      } else {
        option.series[0].data.push(item.monthSellMoney);
        option.series[1].data.push(item.monthSellAmount);

      }

      // 指数 type
      if (_type == 'hot') {
        option.series[2].data.push(item.hotIndexNumber);
        option.series[2].name = '热门指数';
        option.legend.data[2] = '热门指数';
      } else {
        option.series[2].data.push(item.growthIndexNumber);
        option.series[2].name = '增长指数';
        option.legend.data[2] = '增长指数';
      }

    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();


  }

  lineLMInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;

    option.column = this.column;

    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      option.xAxis.data.push(item.date.split(' ')[0]);
      option.series[0].data.push(item.price);
      option.series[1].data.push(item.sellAmount);
    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();

  }


  // 折线图
  lineMMInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;

    option.column = this.column;

    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      option.xAxis.data.push(item.date.split(' ')[0]);
      if (this.appSettings.getSellTimeType() != "month") {
        option.series[0].data.push(item.sellMoney);
        option.series[1].data.push(item.sellAmount);


      } else {
        option.series[0].data.push(item.monthSellMoney);
        option.series[1].data.push(item.monthSellAmount);

      }


    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();
  }

  //
  lineMInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;
    
    option.column = this.column;


    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      option.xAxis.data.push(item.date.split(' ')[0]);
      if (this.appSettings.getSellTimeType() != "month") {
        option.series[0].data.push(item.sellMoney);
        option.series[1].data.push(item.tsellMoney);
        option.series[2].data.push(item.csellMoney);
        option.series[3].data.push(item.thksellMoney);
        option.series[4].data.push(item.gsellMoney);

      } else {
        option.series[0].data.push(item.monthSellMoney);
        option.series[1].data.push(item.monthTSellMoney);
        option.series[2].data.push(item.monthCSellMoney);
        option.series[3].data.push(item.monthThkSellMoney);
        option.series[4].data.push(item.monthGSellMoney);
      }


    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();

  }
  // month折线图
  lineMonthInit() {

    let option = this._service.generate(this.type);


    option.storeData = this.data;

    option.column = this.column;


    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      option.xAxis.data.push(item.date.split(' ')[0]);

      option.series[0].data.push(item.monthSellMoney);
      option.series[1].data.push(item.monthSellAmount);


    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();
  }

  wordInit() {
    let option = this._service.generate(this.type);

    option.storeData = this.data;

    option.fileName = this.title;

    for (let i = 0; i < this.data.length; i++) {

      let item = this.data[i];

      option.series[0].data.push({
        name: item.words,
        value: item.monthSellMoney,
        category: item.categoryId
      });


    }
    // console.log(this.chart);
    this.chart.clear();

    this.chart.setOption(option);
    this.chart.hideLoading();

  }


}
